<?php
namespace app\mini\model;

use app\admin\model\SysModel;
use think\facade\Db;
use app\common\traits\ActionRecordTrait;
use think\Model;
use app\admin\controller\ApiCommon;

use app\crm\model\CustomerLossModel;
use app\crm\model\OrderStatistics;
use app\admin\model\ShopOrderModel;
use app\admin\model\CustomerModel;
use app\admin\model\ShopModel;
use app\shop\model\Refund as OrderModel;
use app\mini\model\MiniStisticsModel;
use app\crm\model\ReserveandLost;



class SysModelMini extends Model

{



    /**

     * @var string

     */

    protected $name = 'admin_sys';



    protected $defaultSoftDelete = 0;



    protected $autoWriteTimestamp = true;








    /**

     * 获取系统首页信息资源

     * @return array

     * @author ran

     * @date 2021-09-23 13:53

     * mailbox 466180170@qq.com

     */

    public function getAdminSysHomeInfoResource($request): array
    {

        $startTime = !empty($request['startTime']) ? strtotime($request['startTime']) : strtotime(date('Y-m-01',time()));
        $endTime = !empty($request['endTime']) ? strtotime($request['endTime'].' 23:59:59') : strtotime(date('Y-m-t 23:59:59',time()));



        $orderModel = new ShopOrderModel();

        $is_shop_array = ['2' => 1,'1' =>2];

        if(is_array($request['shop_id'])){
            $shopIds = $request['shop_id'];
        }else{
            $shopIds = json_decode($request['shop_id'],true) ?? array();
        }

        $adminUserModel = new AdminUser();
        $shop_person_id = $adminUserModel->getPersonId($request['user_id']);
        $sysModel = new SysModel();
        $position_id = $sysModel->getPersonPositionId($shop_person_id);
        $person_id = 0;  //护理师id
        if(!empty($position_id)){
            $person_id = $shop_person_id;
        }

        if(is_array($shopIds)){

            $amountData = []; // 总
            $amountNewData = []; // 新
            $amountRepairData = []; // 补

            foreach ($shopIds as $key => $value) {

                $newShopIds = [];

                array_push($newShopIds,$value);

                $is_medical = Db::name('shop')->where('shop_id',$value)->value('shop_type');

                $isShop = $is_shop_array[$is_medical];

                $newRequest = [];

                $newRequest['startTime'] = $startTime;
                $newRequest['endTime'] = $endTime;
                $newRequest['isShop'] = $isShop;
                $newRequest['shop_person_id'] = $person_id;

                $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

                array_push($amountData,$order['amount']);
                array_push($amountNewData,$order['amountNew']);
                array_push($amountRepairData,$order['amountRepair']);

            }

            $res = [

                'amount' => bcadd(array_sum($amountData),0,2),

                'amountNew' => bcadd(array_sum($amountNewData),0,2),

                'amountRepair' => bcadd(array_sum($amountRepairData),0,2),

            ];

        }else{

            $newShopIds = [];

            array_push($newShopIds,$shopIds);

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->value('shop_type');

            $isShop = $is_shop_array[$is_medical];

            $newRequest = [];

            $newRequest['startTime'] = $startTime;
            $newRequest['endTime'] = $endTime;
            $newRequest['isShop'] = $isShop;
            $newRequest['shop_person_id'] = $person_id;

            $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

            $res = [

                'amount' => bcadd($order['amount'],0,2),  //当前店铺集合支付总金额

                'amountNew' => bcadd($order['amountNew'],0,2), //新单

                'amountRepair' => bcadd($order['amountRepair'],0,2), //补单

            ];
        }

        return $res;

    }

    /**
     * 首页客户数据查询
     */
    public function getHomeCustomer($shopIds,$request): array
    {
        $isShop = $request['isShop'] ?? 0;

        $startTime = !empty($request['startTime']) ? strtotime($request['startTime']) : strtotime(date('Y-m-01',time()));
        $endTime = !empty($request['endTime']) ? strtotime($request['endTime'].' 23:59:59') : strtotime(date('Y-m-t 23:59:59',time()));

        $adminUserModel = new AdminUser();
        $shop_person_id = $adminUserModel->getPersonId($request['user_id']);
        $sysModel = new SysModel();
        $position_id = $sysModel->getPersonPositionId($shop_person_id);
        $person_id = 0;  //护理师id
        if(!empty($position_id)){
            $person_id = $shop_person_id;
        }

        $orderModel = new ShopOrderModel();
        $customerModel = new CustomerModel();

        $customerComeIn = $customerModel->getCustomerCollect('count',$shopIds,$startTime,$endTime,$isShop,$person_id);

        $cjCustomer = $orderModel->getShopOrderCollect('count', $shopIds, $startTime, $endTime, $isShop,$person_id);

        $serNum = 0;
        foreach ($shopIds as $key => $value) {

            // 护理量查询
            $service = Db::name('service_log')->where([['shop_id', '=', $value], ['create_time', 'between', "$startTime,$endTime"],['category_id','in',[1,8,10,11,4,12]]])->count();

            // echo $service;echo "<br/>";

            $serNum = bcadd($serNum,$service,0);

        }

        // exit;

        // if(!empty($service)){

        //     $service = array_column($service,null,'shop_id');

        // }else{

        //     $service[$shopIds[0]]['sum'] = '0';

        // }

        return [

            'customerComeIn' => $customerComeIn,

            'cjCustomer' => $cjCustomer,

            // 'service' => $service[$shopIds[0]]['sum'],

            'service' => $serNum,

        ];
    }


    /**
     * 首页保有数据查询
     */
    public function getHomeBaoyou($shopIds,$request): array
    {

        if(empty($request['shop_id']) && empty($request['user_id'])){
            $tenure = $popularityRate = $gongxiaomanyi =  $baoyouRate =  $warning_customerN=  $lost_customerN = '0.00';
            return [

                'tenure' => $tenure,

                'popularityRate' => $popularityRate,

                'gongxiaomanyi' => $gongxiaomanyi,

                'baoyouRate' => $baoyouRate,

                'warning_customerN' => $warning_customerN,

                'lost_customerN' => $lost_customerN,

            ];
        }

        $adminUserModel = new AdminUser();
        $shop_person_id = $adminUserModel->getPersonId($request['user_id']);
        $sysModel = new SysModel();
        $position_id = $sysModel->getPersonPositionId($shop_person_id);
        $person_where =[];
        if(!empty($position_id)){
            $person_where['nurse_id'] = $shop_person_id;
        }
        // 保有顾客数
        $date = date('Y-m-d',time());

        $model = new ReserveandLost();

        // $cj_customer_all = $model->cj_customer($shopIds,[]);

        $cj_customer = $model->cj_customer($shopIds,$person_where);

        $baoyou_customer = $model->baoyou_customer($cj_customer,$date);

        $warning_customer = $model->warning_customer($cj_customer,$date,'','','');

        $lost_customer = $model->lost_customer($cj_customer,$date);

        $tenure = count($baoyou_customer);

        $warning_customerN = count($warning_customer);

        $lost_customerN = count($lost_customer);



        $shopModel = new ShopModel();
        $shopModeRes = $shopModel->getAdminShopStatistics($shopIds,(int)$request['page']='',(int)$request['limit']='',$request);
        // 项目普及率



        $data = $shopModeRes['list'][0]['list'];

        // echo "<pre>";
        // print_r($shopModeRes);
        // echo "</pre>";
        // exit;

        $popularityRate = bcadd(str_replace('%','',$data[0]['popularityRate']),0,2);
        $gongxiaomanyi = bcadd(str_replace('%','',$data[0]['gongxiaomanyi']),0,2);
        $baoyouRate = count($cj_customer)>0?''.bcdiv(count($baoyou_customer),count($cj_customer),4)*100:0;

        return [

            'tenure' => $tenure,

            'popularityRate' => $popularityRate,

            'gongxiaomanyi' => $gongxiaomanyi,

            'baoyouRate' => $baoyouRate,

            'warning_customerN' => $warning_customerN,

            'lost_customerN' => $lost_customerN,

        ];
    }

    /**
     * 客户的消费记录
     */
    public function costList($request)
    {
        $orderModel = new OrderModel();

        // 收款单
        $skResquest = $request;
        $skResquest['type'] = '3';

        $skData = $orderModel->getDataList($skResquest);

        $skList = isset($skData['list'])?$skData['list']:[];

        // 退款单
        $tkResquest = $request;
        $tkResquest['type'] = '1';

        $tkData = $orderModel->getDataList($tkResquest);

        $tkList = isset($tkData['list'])?$tkData['list']:[];

        $newList = $skList;
        foreach ($tkList as $key => $value) {
            array_push($newList,$value);
        }

        // array_push($newList,$skList);
        // array_push($newList,$tkList);

        $deal_time = array_column($newList, 'deal_time');

        array_multisort($deal_time, SORT_DESC, $newList);

        return [
            'list' => $newList,
        ];
    }

    /**
     * 客户的服务记录
     */
    public function serviceLog($request)
    {

        $startTime = strtotime(date('Y-m-01',time()));
        $endTime = strtotime(date('Y-m-t 23:59:59',time()));
        try {

            $customerId = $request['customer_id'] ?? '';

            $type = $request['type'] ?? '';

            $user_id = $request['user_id'] ?? '';

            $shopIds = $request['shopIds'] ?? '';

            $status = $request['status'] ?? '';

            $searchText = $request['searchText'] ?? '';

            $is_evaluation = $request['is_evaluation'] ?? '';

            $where = [];

            // array_push($where,['create_time','between',"$startTime,$endTime"]);

            if($customerId>0){
                array_push($where,['customer_id','=',$customerId]);
            }

            if($status == '-1'){
                $tagTime = strtotime('-1 month');

                array_push($where,['create_time','>',$tagTime]);

				$shop_person_id = Db::name('shop_person')->where('name','虚拟员工核销专用')->column('id');
				array_push($where,['nurse_id_one','not in',$shop_person_id]);
            }

            if(strlen($is_evaluation) >0){

                array_push($where,['is_evaluation','=',$is_evaluation]);
            }
            array_push($where,['service_type','=',1]);
            // if($is_evaluation != ''){
            //     array_push($where,['is_evaluation','=',$is_evaluation]);
            // }else{
            //     array_push($where,['is_evaluation','is null','']);
            // }

            // 搜索
            if(!empty($searchText)){
                $searchWhere = [];
                array_push($searchWhere,['customer_name|telephone','like',"$searchText%"]);
                array_push($searchWhere,['shop_id','in',$shopIds]);

                $customerSearch = Db::name('customer')->where($searchWhere)->column('id');
                array_push($where,['customer_id','in',$customerSearch]);
            }



            if($type==1){
                $permissions = $this->getPermissions($request);

                if($permissions){
                    // 范围权限
                    array_push($where,['shop_id','in',$shopIds]);
                }else{
                    // 个人权限
                    $shop_person_id = Db::name('admin_user')->where('id',$user_id)->value('shop_person_id');

                    $csutomerIds = Db::name('customer')->where('nurse_id','=',$shop_person_id)->column('id');

                    array_push($where,['customer_id','in',$csutomerIds]);
                }
            }

            $dataCount =  Db::name('service_log')->where($where)->count();

            $serviceLogList =  Db::name('service_log')->where($where)->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->order('id DESC')->select()->toArray();

            $cids = array_values(array_unique(array_column($serviceLogList, 'customer_id')));

            $serviceIds = array_values(array_unique(array_column($serviceLogList, 'service_id')));

            $shop_ids = array_values(array_unique(array_column($serviceLogList, 'shop_id')));

            $nurse_ids1 = array_values(array_unique(array_column($serviceLogList, 'nurse_id_one')));

            $nurse_ids2 = array_values(array_unique(array_column($serviceLogList, 'nurse_id_two')));

            $customerInfo = Db::name('customer')->where('id','in',$cids)->column('customer_name,telephone','id');

//            $serciceCardInfo = Db::name('service')->where('id','in',$serviceIds)->column('name','id');

            $nurse1 = Db::name('shop_person')->where('id','in',$nurse_ids1)->column('name','id');

            $nurse2 = Db::name('shop_person')->where('id','in',$nurse_ids2)->column('name','id');

            $shops = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name','shop_id');

            $list = [];
            
            
            foreach ($serviceLogList as $key => $value)
            {
                $one = [];
                $one['id'] = $value['id'];
            
                $serviceData = DB::name('service')->where('id', $value['service_id'])->field('name,order_id,goods_id')->find();
                $goods_alias_name = '';
                if (!empty($serviceData['order_id'])) {
                    $goods_alias_name = DB::name('shop_order_goods')
                        ->where('order_id', $serviceData['order_id'])
                        ->where('goods_id', $serviceData['goods_id'])
                        ->value('goods_alias_name');
                }
                
                $imageDate = Db::name('service_log_image')->where('log_id', $value['id'])->value('img_url');
                $one['images'] = !empty($imageDate) ? explode(',', $imageDate) : [];
                
                $one['service_id'] = $value['service_id'];
                $one['shop_id'] = $value['shop_id'];
                $one['customer_id'] = $value['customer_id'];
                
                // 安全访问 customerInfo
                $one['customer_name'] = $customerInfo[$value['customer_id']]['customer_name'] ?? '';
                
                $one['service_name'] = !empty($goods_alias_name) ? $goods_alias_name : ($serviceData['name'] ?? '');
                
                // 安全访问 nurse 信息
                $one['nurse1'] = $nurse1[$value['nurse_id_one']] ?? '';
                $one['nurse2'] = $nurse2[$value['nurse_id_two']] ?? '';
                
                $one['create_time'] = $value['create_time'] > 0 ? date('Y-m-d H:i:s', $value['create_time']) : '';
                
                // 安全处理电话号码
                $phone = $customerInfo[$value['customer_id']]['telephone'] ?? '';
                $one['telephone'] = $phone ?? '';
                
                // 安全访问店铺信息
                $one['shop'] = $shops[$value['shop_id']] ?? '';
                $one['is_evaluation'] = $value['is_evaluation'];
            
                $list[] = $one; // 比 array_push 更高效
            }
            $data = [];

            $data['list'] = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return ['data' => $data];

        } catch (\Throwable $e) {
            return ['error' => $e->getMessage()];
        }

    }

    /**
     * 客户管理
     */
    public function getDataList($request)
    {
        $startTime = strtotime(date('Y-m-01',time()));
        $endTime = strtotime(date('Y-m-t 23:59:59',time()));

        $permissions = $this->getPermissions($request);

        $where = [];
        $result = [];

        $adminUserModel = new AdminUser();
        $shop_person_id = $adminUserModel->getPersonId($request['user_id']);
        $sysModel = new SysModel();
        $position_id = $sysModel->getPersonPositionId($shop_person_id);
        $person_data=[];
        if(!empty($position_id)){
            array_push($where,['nurse_id','=',$shop_person_id]);
            $person_data['nurse_id'] = $shop_person_id;
        }

        if($permissions){
            // $data = '范围数据(true)';
            array_push($where,['shop_id','in',$request['shopIds']]);
        }else{
            // $data = '个人数据(false)';
            array_push($where,['shop_id','in',$request['shopIds']]);
            array_push($where,['nurse_id','=',$request['user_id']]);
        }

        // 预约未进店
        $num1 = Db::name('customer')->where($where)
                ->where('first_time','<',1)
                ->where('second_time','<',1)
                ->where('create_time','between',"$startTime,$endTime")
                ->count();


        // ------------------------------------------------------------
        $model = new ReserveandLost();
        $date = date('Y-m-d',time());



        // 成交顾客id
        $cj_customer = $model->cj_customer($request['shopIds'],$person_data);


        //流失预警
        $liushiyujing = $model->warning_customer($cj_customer,$date,'','','');
        $num2 = count($liushiyujing);

        // 流失顾客
        $lost_customer = $model->lost_customer($cj_customer,$date);
        $num3 = count($lost_customer);

        // 流失预警
        // $customerLossModel = new CustomerLossModel();
        // $liushiyujing = [
        //     'is_join_shop' => 4,
        //     'shopIds' => $request['shopIds'],
        //     'user_id' => $request['user_id'],
        //     'onlyDataCounts' => 'yes',
        // ];

        // $dataList = $customerLossModel->getDataList($liushiyujing);
        // $num2 = $dataList['dataCounts'];


        // 流失顾客
        // $liushiguke = [
        //     'is_join_shop' => 3,
        //     'shopIds' => $request['shopIds'],
        //     'user_id' => $request['user_id'],
        //     'onlyDataCounts' => 'yes',
        // ];
        // $dataList = $customerLossModel->getDataList($liushiguke);
        // $num3 = $dataList['dataCounts'];

        // 新客未成交
        $num4 = Db::name('customer')->where($where)
                ->where('cj_time','<',1)
                ->where('first_time|second_time','between',"$startTime,$endTime")
                ->count();

        // 生日提醒
        $birthdayStr = strtotime('+1 week');
        $nowTime = time();
        $num5 = Db::name('customer')->where($where)
                ->where('membership_leve','>',0)
                ->where('birthday','between',"$nowTime,$birthdayStr")
                ->count();

        //

        $result = [
            '0' => [
                'title' => '预约未进店',
                'content' => '提醒昨天和今天未到店的客户',
                'icon' => '2.png',
                'num' => $num1,
                'function' => 'noComeIn'
            ],
            '1' => [
                'title' => '流失预警',
                'content' => '截至到当前事件1个月内未消费顾客书',
                'icon' => '1.png',
                'num' => $num2,
                'function' => 'liushiyj'
            ],
            '2' => [
                'title' => '流失客户',
                'content' => '截至到当前事件4个月内未消费顾客书',
                'icon' => '3.png',
                'num' => $num3,
                'function' => 'liushikh'
            ],
            '3' => [
                'title' => '新客未成交',
                'content' => '当月进店且未成交的顾客',
                'icon' => '2.png',
                'num' => $num4,
                'function' => 'noCJ'
            ],
            '4' => [
                'title' => '生日提醒',
                'content' => '近7天过生日的会员客户',
                'icon' => '4.png',
                'num' => $num5,
                'function' => 'birthday'
            ]

        ];

        return ['list' => $result];
    }

    // 获取数据范围权限
    public function getPermissions($request){
        $where = [];
        array_push($where,['id','=',$request['user_id']]);
        $group_id = Db::name('admin_user')->where($where)->value('group_id');

        $hulishis = [74,76,77,78,79,80,98,104,107];

        if(in_array($group_id,$hulishis)){
            $permissions = false; // 个人数据
        }else{
            $permissions = true; // 范围数据
        }

        return $permissions;
    }

    // 添加客户标签
    public function addTag($request){

        $create_time = date('Y-m-d h:i:s',time());

        $where = [];

        array_push($where,['tag_name','=',$request['tagValue']]);
        array_push($where,['customer_id','=',$request['customer_id']]);

        $tagInfo = Db::name('customer_tag')->where($where)->find();

        if(empty($tagInfo)){
            $data = [
                'id'          => '',
                'tag_name'    => $request['tagValue'],
                'customer_id' => $request['customer_id'],
                'staff_name'  => $request['staff_name'],
                'create_time' => $create_time,
                'type'        => 0,
            ];

            $tagId = Db::name('customer_tag')->insertGetId($data);

            $msg = '添加成功！';
        }else{
            $msg = '标签重复！';
        }




        return ['result' => $msg];
    }

    // 获取客户标签
    public function getTag($request){

        $where = [];

        array_push($where,['customer_id','=',$request['customer_id']]);
        array_push($where,['type','=',0]);

        $tagArr = Db::name('customer_tag')->where($where)->column('id,tag_name');

        return ['result' => $tagArr];
    }

    // 删除客户标签
    public function deleteTag($request){
        $data['type'] = 1;

        $bool = Db::name('customer_tag')->where(['id'=>$request['id']])->update($data);

        if ($bool !== false) {
            return ['error' => '操作成功', 'data' => []];
        }else{
            return ['error' => '操作失败', 'data' => []];
        }
    }


    // 获取客户列表
    public function getCaseCustomer($request){

        $where = [];

        $customer_id = $request['customer_id'];

        array_push($where,['id','=',$customer_id]);

        // echo "<pre>";
        // print_r($where);
        // echo "</pre>";
        // exit;
        $sex = ['1' => '男', '2' => '女'];

        $customer_list = Db::name('customer')->where($where)->find();

        $customer_list['sex_title'] = $sex[$customer_list['sex']];

        return $customer_list;
    }

    // 员工小程序数据模块-经营数据
    public function getShopStistics($request){

        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));
            $endTime = strtotime(date('Y-m-t 23:59:59',time()));

            $request['startTime'] = $startTime;
            $request['endTime'] = $endTime;

            $st = date('Y-m-01',time());

            $et = date('Y-m-t',time());

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

                $st = $request['time'];

                $et = $request['time'];

            }else{
                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        $orderModel = new ShopOrderModel();

        $shopModel = new ShopModel();

        // $order = $orderModel->miniHomeOrder($shopIds, $request);

        $is_shop_array = ['2' => 1,'1' =>2];

        $shopIds = json_decode($request['shop_id'],true) ?? array();

        if(is_array($shopIds)){

            $amountData = []; // 总
            $amountNewData = []; // 新
            $amountRepairData = []; // 补
            $amountSData = []; // 实
            $referralData = []; // 转
            $scarData = []; // 疤
            $projectData = []; // 项

            foreach ($shopIds as $key => $value) {
                $newShopIds = [];

                array_push($newShopIds,$value);

                $is_medical = Db::name('shop')->where('shop_id',$value)->value('shop_type');

                $isShop = $is_shop_array[$is_medical];

                $newRequest = [];

                $newRequest['startTime'] = $st;
                $newRequest['endTime'] = $et;
                $newRequest['isShop'] = $isShop;

                $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

                $shopModelRequest['start_time'] = $st;
                $shopModelRequest['end_time'] = $et;

                $shopModelData = $shopModel->readAdminShopAchievementStatistics($newShopIds,(int)$request['page']="",(int)$request['limit']="",$shopModelRequest);

                $sData = $shopModelData['list'];

                array_push($amountData,$order['amount']);
                array_push($amountNewData,$order['amountNew']);
                array_push($amountRepairData,$order['amountRepair']);

                array_push($amountSData,$sData[0]['amount']);
                array_push($referralData,$sData[0]['referralMoney']);
                array_push($scarData,$sData[0]['scarMoney']);
                array_push($projectData,$sData[0]['projectMoney']);

            }

            // echo "<pre>";
            // print_r($amountData);
            // echo "</pre>";
            // exit;

            $res = [
                'amount' => bcadd(array_sum($amountData),0,2),

                'amountNew' => bcadd(array_sum($amountNewData),0,2),

                'amountRepair' => bcadd(array_sum($amountRepairData),0,2),

                'amountS' => bcadd(array_sum($amountSData),0,2),

                'referral' => bcadd(array_sum($referralData),0,2),

                'scar' => bcadd(array_sum($scarData),0,2),

                'project' => bcadd(array_sum($projectData),0,2),
            ];

        }else{

            $newShopIds = [];

            array_push($newShopIds,$shopIds);

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->value('shop_type');

            $isShop = $is_shop_array[$is_medical];

            $newRequest = [];

            $newRequest['startTime'] = $startTime;
            $newRequest['endTime'] = $endTime;
            $newRequest['isShop'] = $isShop;

            $order = $orderModel->miniHomeOrder($newShopIds, $newRequest);

            $shopModelRequest['start_time'] = $st;
            $shopModelRequest['end_time'] = $et;

            $shopModelData = $shopModel->readAdminShopAchievementStatistics($newShopIds,(int)$request['page']="",(int)$request['limit']="",$shopModelRequest);

            $sData = $shopModelData['list'];

            // echo "<pre>";
            // print_r($shopModelData);
            // echo "</pre>";
            // exit;

            $res = [
                'amount' => bcadd($order['amount'],0,2),  //当前店铺集合支付总金额

                'amountNew' => bcadd($order['amountNew'],0,2), //新单

                'amountRepair' => bcadd($order['amountRepair'],0,2), //补单

                'amountS' => bcadd($sData[0]['amount'],0,2), //实收

                'referral' => bcadd($sData[0]['referralMoney'],0,2), //转诊

                'scar' => bcadd($sData[0]['scarMoney'],0,2), //疤痕

                'project' => bcadd($sData[0]['projectMoney'],0,2), //项目
            ];

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-新单数据
    public function getShopStistics1($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        $person_id = $request['shop_person_id'];

        $model = new OrderStatistics();
        $shopModel = new ShopModel();
        $nine_start_time = 1725120000; //24年9月1日 0：00：00
        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountNewData = []; // 新单
            foreach ($shopIds as $key => $value) {
                $newsXDMoney = 0;
                $is_medical = Db::name('shop')->where('shop_id',$value)->field('shop_type,market_id')->find();

                if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                    //走一批
                    if ($is_medical['shop_type'] == 1) {
                        $mzXDMoneyAllOne = $shopModel->outpatientPerform([$value],1,$startTime,$endTime); //门诊新单业绩
                        $XDMoney = empty($mzXDMoneyAllOne[$value]) ? 0 : $mzXDMoneyAllOne[$value];
                    }else{
                        $shopXDMoneyAllOne = $shopModel->shopPerform([$value],1,$startTime,$endTime);//门店新单业绩
                        $XDMoney = empty($shopXDMoneyAllOne[$value]) ? 0 : $shopXDMoneyAllOne[$value];
                    }
                }else{
                    //走两批
                    $XDMoney = 0;
                    if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                        //新的计算规则
                        if ($is_medical['shop_type'] == 1) {
                            //门诊
                            $mzXDMoneyAllOne = $shopModel->outpatientPerform([$value],1,$nine_start_time,$endTime); //门诊新单业绩
                            $XDMoney = empty($mzXDMoneyAllOne[$value]) ? 0 : $mzXDMoneyAllOne[$value];
                        } else {
                            //门店
                            $shopXDMoneyAllOne = $shopModel->shopPerform([$value],1,$nine_start_time,$endTime);//门店新单业绩
                            $XDMoney = empty($shopXDMoneyAllOne[$value]) ? 0 : $shopXDMoneyAllOne[$value];
                        }
                        $endTime = 1725119999; //24年8月31日 23 59 59
                    }


                    if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){
                        // 川渝地区
                        $newsXDMoney = $model->sumShopPayMoneyNewMZ('XD',$value,$is_medical['shop_type'],$startTime,$endTime);
                    }else{
                        // 非川渝地区
                        $newsXDMoney = $model->sumShopPayMoneyNew('XD',$value,$is_medical['shop_type'],$startTime,$endTime);
                    }
                }

                array_push($amountNewData,$XDMoney);
                array_push($amountNewData,$newsXDMoney);
            }

            $res = bcadd(array_sum($amountNewData),0,2);

        }else{


            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();
            $newsXDMoney = 0;
            if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){

                //走一批
                if ($is_medical['shop_type'] == 1) {
                    $mzXDMoneyAllOne = $shopModel->outpatientPerform([$shopIds],1,$startTime,$endTime,$person_id); //门诊新单业绩
                    $XDMoney = empty($mzXDMoneyAllOne[$shopIds]) ? 0 : $mzXDMoneyAllOne[$shopIds];
                }else{
                    $shopXDMoneyAllOne = $shopModel->shopPerform([$shopIds],1,$startTime,$endTime,0,0,$person_id);//门店新单业绩

                    $XDMoney = empty($shopXDMoneyAllOne[$shopIds]) ? 0 : $shopXDMoneyAllOne[$shopIds];
                }
            }else{
                $XDMoney = 0;
                if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                    //出现跨天的
                    //新的计算规则
                    if ($is_medical['shop_type'] == 1) {
                        $mzXDMoneyAllOne = $shopModel->outpatientPerform([$shopIds],1,$nine_start_time,$endTime,$person_id); //门诊新单业绩
                        $XDMoney = empty($mzXDMoneyAllOne[$value['shop_id']]) ? 0 : $mzXDMoneyAllOne[$shopIds];
                    } else {
                        $shopXDMoneyAllOne = $shopModel->shopPerform([$shopIds],1,$nine_start_time,$endTime,0,0,$person_id);//门店新单业绩
                        $XDMoney = empty($shopXDMoneyAllOne[$shopIds]) ? 0 : $shopXDMoneyAllOne[$shopIds];
                    }
                    $endTime = 1725119999; //24年8月31日 23 59 59
                }
                //走两批
                if($is_medical['market_id'] == 8 || $is_medical['market_id'] == 9 || $is_medical['market_id'] == 10 || $is_medical['market_id'] == 11){
                    // 川渝地区
                    $newsXDMoney = $model->sumShopPayMoneyNewMZ('XD',$shopIds,$is_medical['shop_type'],$startTime,$endTime,$person_id);
                }else{
                    // 非川渝地区
                    $newsXDMoney = $model->sumShopPayMoneyNew('XD',$shopIds,$is_medical['shop_type'],$startTime,$endTime,$person_id);
                }
            }

            $res = bcadd($newsXDMoney,$XDMoney,2);

        }

        return $res;

    }



    // 员工小程序-数据-经营数据-补单数据
    public function getShopStistics2($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];
        $person_id = $request['shop_person_id'];

        $model = new OrderStatistics();
        $shopModel = new ShopModel();
        $nine_start_time = 1725120000; //24年9月1日 0：00：00

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountNewData = []; // 补单
            $shopData = DB::name('shop')->whereIn('shop_id',$shopIds)->field('shop_type,market_id,shop_id')->select()->toArray();
            foreach ($shopData as $key => $val) {
                $shop_ids = [$val['shop_id']];
                $shop_id = $val['shop_id'];
                $market_id = $val['market_id'];
                $shop_type = $val['shop_type'];
                $newsBDMoney = 0;
                if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                    //走一批
                    if ($val['shop_type'] == 1) {
                        $mzBDMoneyAllOne = $shopModel->outpatientPerform($shop_ids,2,$startTime,$endTime); //门诊补单业绩
                        $BDMoney = empty($mzBDMoneyAllOne[$shop_id]) ? 0 : $mzBDMoneyAllOne[$shop_id];
                    }else{
                        $shopBDMoneyAllOne = $shopModel->shopPerform($shop_ids,2,$startTime,$endTime);//门店补单业绩
                        $BDMoney = empty($shopBDMoneyAllOne[$shop_id]) ? 0 : $shopBDMoneyAllOne[$shop_id];
                    }
                }else{
                    $BDMoney = 0;
                    if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                        //新的计算规则
                        if ($val['shop_type'] == 1) {
                            //门诊
                            $mzBDMoneyAllOne = $shopModel->outpatientPerform($shop_ids,2,$nine_start_time,$endTime); //门诊补单业绩
                            $BDMoney = empty($mzBDMoneyAllOne[$shop_id]) ? 0 : $mzBDMoneyAllOne[$shop_id];
                        } else {
                            //门店
                            $shopBDMoneyAllOne = $shopModel->shopPerform($shop_ids,2,$nine_start_time,$endTime);//门店补单业绩
                            $BDMoney = empty($shopBDMoneyAllOne[$shop_id]) ? 0 : $shopBDMoneyAllOne[$shop_id];
                        }
                        $endTime = 1725119999; //24年8月31日 23 59 59
                    }
                    //走两批
                    if(in_array($market_id,[8,9,10,11])){
                        // 川渝地区
                        $newsBDMoney = $model->sumShopPayMoneyNewMZ('BD',$shop_id,$shop_type,$startTime,$endTime);
                    }else{
                        // 非川渝地区
                        $newsBDMoney = $model->sumShopPayMoneyNew('BD',$shop_id,$shop_type,$startTime,$endTime);
                    }
                }

                array_push($amountNewData,$BDMoney);
                array_push($amountNewData,$newsBDMoney);
            }
            $res = bcadd(array_sum($amountNewData),0,2);

        }else{

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();
            $newsBDMoney = 0;
            if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                //走一批
                if ($is_medical['shop_type'] == 1) {
                    $mzBDMoneyAllOne = $shopModel->outpatientPerform([$shopIds],2,$startTime,$endTime,$person_id); //门诊补单业绩
                    $BDMoney = empty($mzBDMoneyAllOne[$shopIds]) ? 0 : $mzBDMoneyAllOne[$shopIds];
                }else{
                    $shopBDMoneyAllOne = $shopModel->shopPerform([$shopIds],2,$startTime,$endTime,0,0,$person_id);//门店补单业绩
                    $BDMoney = empty($shopBDMoneyAllOne[$shopIds]) ? 0 : $shopBDMoneyAllOne[$shopIds];
                }
            }else{
                $BDMoney = 0;
                if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                    //新的计算规则
                    if ($is_medical['shop_type'] == 1) {
                        $mzBDMoneyAllOne = $shopModel->outpatientPerform([$shopIds],2,$nine_start_time,$endTime,$person_id); //门诊新单业绩
                        $BDMoney = empty($mzBDMoneyAllOne[$value['shop_id']]) ? 0 : $mzBDMoneyAllOne[$shopIds];
                    } else {
                        $shopBDMoneyAllOne = $shopModel->shopPerform([$shopIds],2,$nine_start_time,$endTime,0,0,$person_id);//门店补单业绩
                        $BDMoney = empty($shopBDMoneyAllOne[$shopIds]) ? 0 : $shopBDMoneyAllOne[$shopIds];
                    }
                    $endTime = 1725119999; //24年8月31日 23 59 59
                }
                //走两批
                if(in_array($is_medical['market_id'],[8,9,10,11])){
                    // 川渝地区
                    $newsBDMoney = $model->sumShopPayMoneyNewMZ('BD',$shopIds,$is_medical['shop_type'],$startTime,$endTime,$person_id);
                }else{
                    // 非川渝地区
                    $newsBDMoney = $model->sumShopPayMoneyNew('BD',$shopIds,$is_medical['shop_type'],$startTime,$endTime,$person_id);
                }

            }

            $res = bcadd($newsBDMoney,$BDMoney,2);

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-实收业绩
    public function getShopStistics3($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];

        $person_id = $request['shop_person_id'];

        $nine_start_time = 1725120000; //24年9月1日 0：00：00

        $shopModel = new ShopModel();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $shopData = DB::name('shop')->whereIn('shop_id',$shopIds)->field('shop_type,market_id,shop_id')->select()->toArray();
            $amountShiShou = [];
            foreach ($shopData as $key => $val) {
                $shop_ids = [$val['shop_id']];
                $shop_id = $val['shop_id'];
                $shiShouMoney = 0;
                if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                    //走一批
                    if($val['shop_type']==1){
                        $outpatient_shi = $shopModel->OutpatientActualPerform($shop_ids,$startTime,$endTime);//门诊实收业绩
                        $shi = empty($outpatient_shi[$shop_id]) ? 0 : $outpatient_shi[$shop_id];
                    } else{
                        $shop_shi = $shopModel->ShopActualPerform($shop_ids,$startTime,$endTime);//门店实收业绩
                        $shi = empty($shop_shi[$shop_id]) ? 0 : $shop_shi[$shop_id];
                    }
                }else{
                    $shi = 0;
                    if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                        //走两批
                        if($val['shop_type']==1){
                            $outpatient_shi = $shopModel->OutpatientActualPerform($shop_ids,$nine_start_time,$endTime);//门诊实收业绩
                            $shi = empty($outpatient_shi[$shop_id]) ? 0 : $outpatient_shi[$shop_id];
                        } else{
                            $shop_shi = $shopModel->ShopActualPerform($shop_ids,$nine_start_time,$endTime);//门店实收业绩
                            $shi = empty($shop_shi[$shop_id]) ? 0 : $shop_shi[$shop_id];
                        }
                        $endTime = 1725119999; //24年8月31日 23 59 59
                    }
                    $shiShouMoney = $shopModel->amountMoneyAll($val['shop_id'],$startTime,$endTime);
                }


                array_push($amountShiShou,$shi);
                array_push($amountShiShou,$shiShouMoney);

            }

            $res = bcadd(array_sum($amountShiShou),0,2);

        }else{
            $shopData = DB::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id,shop_id')->find();
            $shop_ids = [$shopIds];
            $shiShouMoney = 0;
            if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){

                if($shopData['shop_type']==1){
                    $outpatient_shi = $shopModel->OutpatientActualPerform($shop_ids,$startTime,$endTime,$person_id);//门诊实收业绩
                    $shi = empty($outpatient_shi[$shopIds]) ? 0 : $outpatient_shi[$shopIds];
                } else{
                    $shop_shi = $shopModel->ShopActualPerform($shop_ids,$startTime,$endTime,$person_id);//门店实收业绩
                    $shi = empty($shop_shi[$shopIds]) ? 0 : $shop_shi[$shopIds];
                }

            }else{
                //走两批
                $shi = 0;
                if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                    if($shopData['shop_type']==1){
                        $outpatient_shi = $shopModel->OutpatientActualPerform($shop_ids,$nine_start_time,$endTime,$person_id);//门诊实收业绩
                        $shi = empty($outpatient_shi[$shopIds]) ? 0 : $outpatient_shi[$shopIds];
                    } else{
                        $shop_shi = $shopModel->ShopActualPerform($shop_ids,$nine_start_time,$endTime,$person_id);//门店实收业绩
                        $shi = empty($shop_shi[$shopIds]) ? 0 : $shop_shi[$shopIds];
                    }
                    $endTime = 1725119999; //24年8月31日 23 59 59
                }
                $shiShouMoney = $shopModel->amountMoneyAll($shopIds,$startTime,$endTime,$person_id);
            }
            $res = bcadd($shiShouMoney,$shi,2);
        }

        return $res;

    }

    // 员工小程序-数据-经营数据-转诊业绩
    public function getShopStistics4($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];
        $person_id = $request['shop_person_id'];

        $shopModel = new ShopModel();
        $nine_start_time = 1725120000; //24年9月1日 0：00：00

        if(is_array($shopIds)){ // 市场经理以及总部只能权限
            $amountZhuanZhen = []; // 转诊

            $shopData = DB::name('shop')->whereIn('shop_id',$shopIds)->field('shop_type,market_id,shop_id')->select()->toArray();
            foreach ($shopData as $key => $val) {
                $market_id = $val['market_id'];
                $shop_type = $val['shop_type'];
                $shop_id = $val['shop_id'];
                $shop_ids = [$shop_id];

                $referralMoney = 0; //川渝地区无转诊
                if(!in_array($market_id,[8,9,10,11])){
                    if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                        if($val['shop_type'] == 1){
                            $outpatient_zhuan = $shopModel->OutpatientReferralPerform($shop_ids,$startTime,$endTime); //门诊转诊业绩
                            $zhuan = empty($outpatient_zhuan[$shop_id]) ? 0 : $outpatient_zhuan[$shop_id];
                        }else{
                            $shop_zhuan = $shopModel->shopReferralPerform($shop_ids,$startTime,$endTime); //门店转诊业绩
                            $zhuan = empty($shop_zhuan[$shop_id]) ? 0 : $shop_zhuan[$shop_id];
                        }
                    }else{
                        $zhuan = 0;
                        if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                            if($val['shop_type'] == 1){
                                $outpatient_zhuan = $shopModel->OutpatientReferralPerform($shop_ids,$nine_start_time,$endTime); //门诊转诊业绩
                                $zhuan = empty($outpatient_zhuan[$shop_id]) ? 0 : $outpatient_zhuan[$shop_id];
                            }else{
                                $shop_zhuan = $shopModel->shopReferralPerform($shop_ids,$nine_start_time,$endTime); //门店转诊业绩
                                $zhuan = empty($shop_zhuan[$shop_id]) ? 0 : $shop_zhuan[$shop_id];
                            }
                            $endTime = 1725119999; //24年8月31日 23 59 59
                        }
                        // 非川渝地区
                        $referralMoney = $shopModel->referralMoney($val['shop_id'],$shop_type,$startTime,$endTime);
                    }


                }
                array_push($amountZhuanZhen,$zhuan);
                array_push($amountZhuanZhen,$referralMoney);
            }

            $res = bcadd(array_sum($amountZhuanZhen),0,2);

        }else{

            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();
            $market_id = $is_medical['market_id'];
            $shop_type = $is_medical['shop_type'];
            $shop_id = $shopIds;
            $shop_ids = [$shopIds];
            $referralMoney = 0;    // 川渝地区 无转诊业绩
            if(!in_array($market_id,[8,9,10,11])){
                if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                    if($shop_type == 1){
                        $outpatient_zhuan = $shopModel->OutpatientReferralPerform($shop_ids,$startTime,$endTime,$person_id); //门诊转诊业绩
                        $zhuan = empty($outpatient_zhuan[$shop_id]) ? 0 : $outpatient_zhuan[$shop_id];
                    }else{
                        $shop_zhuan = $shopModel->shopReferralPerform($shop_ids,$startTime,$endTime,$person_id); //门店转诊业绩
                        $zhuan = empty($shop_zhuan[$shop_id]) ? 0 : $shop_zhuan[$shop_id];
                    }
                }else{
                    $zhuan = 0;
                    if( $startTime < $nine_start_time && $endTime > $nine_start_time) {
                        if ($shop_type == 1) {
                            $outpatient_zhuan = $shopModel->OutpatientReferralPerform($shop_ids, $nine_start_time, $endTime, $person_id); //门诊转诊业绩
                            $zhuan = empty($outpatient_zhuan[$shop_id]) ? 0 : $outpatient_zhuan[$shop_id];
                        } else {
                            $shop_zhuan = $shopModel->shopReferralPerform($shop_ids, $nine_start_time, $endTime, $person_id); //门店转诊业绩
                            $zhuan = empty($shop_zhuan[$shop_id]) ? 0 : $shop_zhuan[$shop_id];
                        }
                        $endTime = 1725119999; //24年8月31日 23 59 59
                    }
                    // 非川渝地区
                    $referralMoney = $shopModel->referralMoney($shopIds,$shop_type,$startTime,$endTime);
                }

            }
            $res = bcadd($referralMoney,$zhuan,2);
        }
        return $res;
    }

    // 员工小程序-数据-经营数据-疤痕业绩
    public function getShopStistics5($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];
        $person_id = $request['shop_person_id'];

        $nine_start_time = 1725120000; //24年9月1日 0：00：00

        $shopModel = new ShopModel();

        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountScar = []; // 转诊
            $shopData = DB::name('shop')->whereIn('shop_id',$shopIds)->field('shop_type,market_id,shop_id')->select()->toArray();
            foreach ($shopData as $key => $val) {
                $market_id = $val['market_id'];
                $shop_type = $val['shop_type'];
                $shop_id = $val['shop_id'];
                $shop_ids = [$shop_id];
                $scarMoney = 0;
                if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                    if($val['shop_type'] == 1){
                        $mzBHProject = $shopModel->outpatientPersformProject($shop_ids,$startTime,$endTime,1); //门诊疤痕业绩
                        $bh = empty($mzBHProject[$shop_id]) ? 0 : $mzBHProject[$shop_id];
                    }else{
                        $shopBHProject = $shopModel->shopPerform($shop_ids,0,$startTime,$endTime,1); //门店疤痕业绩
                        $bh = empty($shopBHProject[$shop_id]) ? 0 : $shopBHProject[$shop_id];
                    }
                }else{
                    $bh = 0;
                    if( $startTime < $nine_start_time && $endTime > $nine_start_time) {
                        if($val['shop_type'] == 1){
                            $mzBHProject = $shopModel->outpatientPersformProject($shop_ids,$nine_start_time,$endTime,1); //门诊疤痕业绩
                            $bh = empty($mzBHProject[$shop_id]) ? 0 : $mzBHProject[$shop_id];
                        }else{
                            $shopBHProject = $shopModel->shopPerform($shop_ids,0,$nine_start_time,$endTime,1); //门店疤痕业绩
                            $bh = empty($shopBHProject[$shop_id]) ? 0 : $shopBHProject[$shop_id];
                        }
                        $endTime = 1725119999; //24年8月31日 23 59 59
                    }
                    if(in_array($market_id,[8,9,10,11])){
                        // 川渝地区
                        $scarMoney = $shopModel->sumShopPayMoneyNewMZ('Bh',$shop_id,$shop_type,$startTime,$endTime);
                    }else{
                        // 非川渝地区
                        $scarMoney = $shopModel->sumShopPayMoneyNew('Bh',$shop_id,$shop_type,$startTime,$endTime);
                    }

                }

                array_push($amountScar,$bh);

                array_push($amountScar,$scarMoney);

            }

            $res = bcadd(array_sum($amountScar),0,2);

        }else{
            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();
            $market_id = $is_medical['market_id'];
            $shop_type = $is_medical['shop_type'];
            $shop_id = $shopIds;
            $shop_ids = [$shopIds];
            $scarMoney = 0;
            if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                if($shop_type == 1){
                    $mzBHProject = $shopModel->outpatientPersformProject($shop_ids,$startTime,$endTime,1,$person_id); //门诊疤痕业绩
                    $bh = empty($mzBHProject[$shop_id]) ? 0 : $mzBHProject[$shop_id];
                }else{
                    $shopBHProject = $shopModel->shopPerform($shop_ids,0,$startTime,$endTime,1,0,$person_id); //门店疤痕业绩
                    $bh = empty($shopBHProject[$shop_id]) ? 0 : $shopBHProject[$shop_id];
                }
            }else{
                $bh = 0;
                if( $startTime < $nine_start_time && $endTime > $nine_start_time) {
                    if ($shop_type == 1) {
                        $mzBHProject = $shopModel->outpatientPersformProject($shop_ids, $nine_start_time, $endTime, 1, $person_id); //门诊疤痕业绩
                        $bh = empty($mzBHProject[$shop_id]) ? 0 : $mzBHProject[$shop_id];
                    } else {
                        $shopBHProject = $shopModel->shopPerform($shop_ids, 0, $nine_start_time, $endTime, 1, 0, $person_id); //门店疤痕业绩
                        $bh = empty($shopBHProject[$shop_id]) ? 0 : $shopBHProject[$shop_id];
                    }
                    $endTime = 1725119999; //24年8月31日 23 59 59
                }
                if(in_array($market_id,[8,9,10,11])){
                    // 川渝地区
                    $scarMoney = $shopModel->sumShopPayMoneyNewMZ('Bh',$shop_id,$shop_type,$startTime,$endTime,$person_id);
                }else{
                    // 非川渝地区
                    $scarMoney = $shopModel->sumShopPayMoneyNew('Bh',$shop_id,$shop_type,$startTime,$endTime,$person_id);
                }

            }


            $res = bcadd($scarMoney,$bh,2);

        }

        return $res;

    }

    // 员工小程序-数据-经营数据-项目业绩
    public function getShopStistics6($request){

        $conditions = $this->getTime($request);

        $startTime = $conditions['startTime'];
        $endTime = $conditions['endTime'];
        $shopIds = $conditions['shopIds'];
        $person_id = $request['shop_person_id'];

        $shopModel = new ShopModel();
        $nine_start_time = 1725120000; //24年9月1日 0：00：00
        if(is_array($shopIds)){ // 市场经理以及总部只能权限

            $amountProject = []; // 转诊

            $shopData = DB::name('shop')->whereIn('shop_id',$shopIds)->field('shop_type,market_id,shop_id')->select()->toArray();

            foreach ($shopData as $key => $val) {
                $market_id = $val['market_id'];
                $shop_type = $val['shop_type'];
                $shop_id = $val['shop_id'];
                $shop_ids = [$shop_id];
                $projectMoney = 0;
                if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                    if($shop_type == 1){
                        $mzXMProject = $shopModel->outpatientPersformProject($shop_ids,$startTime,$endTime,2); //门诊疤痕业绩
                        $xm = empty($mzXMProject[$shop_id]) ? 0 : $mzXMProject[$shop_id];
                    }else{
                        $shopXMProject = $shopModel->shopPerform($shop_ids,0,$startTime,$endTime,2); //门店疤痕业绩
                        $xm = empty($shopXMProject[$shop_id]) ? 0 : $shopXMProject[$shop_id];
                    }
                }else{
                    $xm = 0;
                    if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                        if($shop_type == 1){
                            $mzXMProject = $shopModel->outpatientPersformProject($shop_ids,$nine_start_time,$endTime,2); //门诊疤痕业绩
                            $xm = empty($mzXMProject[$shop_id]) ? 0 : $mzXMProject[$shop_id];
                        }else{
                            $shopXMProject = $shopModel->shopPerform($shop_ids,0,$nine_start_time,$endTime,2); //门店疤痕业绩
                            $xm = empty($shopXMProject[$shop_id]) ? 0 : $shopXMProject[$shop_id];
                        }
                        $endTime = 1725119999; //24年8月31日 23 59 59
                    }
                    if(in_array($market_id,[8,9,10,11])){
                        // 川渝地区
                        $projectMoney = $shopModel->sumShopPayMoneyNewMZ('XM',$shop_id,$shop_type,$startTime,$endTime);
                    }else{
                        // 非川渝地区
                        $projectMoney = $shopModel->sumShopPayMoneyNew('XM',$shop_id,$shop_type,$startTime,$endTime);
                    }
                }

                array_push($amountProject,$xm);
                array_push($amountProject,$projectMoney);

            }

            $res = bcadd(array_sum($amountProject),0,2);

        }else{
            $is_medical = Db::name('shop')->where('shop_id',$shopIds)->field('shop_type,market_id')->find();
            $market_id = $is_medical['market_id'];
            $shop_type = $is_medical['shop_type'];
            $shop_id = $shopIds;
            $shop_ids = [$shopIds];
            $projectMoney = 0;
            if( $startTime >= $nine_start_time && $endTime > $nine_start_time ){
                if($shop_type == 1){
                    $mzXMProject = $shopModel->outpatientPersformProject($shop_ids,$startTime,$endTime,2,$person_id); //门诊项目业绩
                    $xm = empty($mzXMProject[$shop_id]) ? 0 : $mzXMProject[$shop_id];
                }else{
                    $shopXMProject = $shopModel->shopPerform($shop_ids,0,$startTime,$endTime,2,0,$person_id); //门店项目业绩
                    $xm = empty($shopXMProject[$shop_id]) ? 0 : $shopXMProject[$shop_id];
                }
            }else{
                $xm = 0;
                if( $startTime < $nine_start_time && $endTime > $nine_start_time){
                    if($shop_type == 1){
                        $mzXMProject = $shopModel->outpatientPersformProject($shop_ids,$nine_start_time,$endTime,2,$person_id); //门诊项目业绩
                        $xm = empty($mzXMProject[$shop_id]) ? 0 : $mzXMProject[$shop_id];
                    }else{
                        $shopXMProject = $shopModel->shopPerform($shop_ids,0,$nine_start_time,$endTime,2,0,$person_id); //门店项目业绩
                        $xm = empty($shopXMProject[$shop_id]) ? 0 : $shopXMProject[$shop_id];
                    }
                    $endTime = 1725119999; //24年8月31日 23 59 59
                }
                if(in_array($market_id,[8,9,10,11])){
                    // 川渝地区
                    $projectMoney = $shopModel->sumShopPayMoneyNewMZ('XM',$shop_id,$shop_type,$startTime,$endTime,$person_id);
                }else{
                    // 非川渝地区
                    $projectMoney = $shopModel->sumShopPayMoneyNew('XM',$shop_id,$shop_type,$startTime,$endTime,$person_id);
                }
            }

            $res = bcadd($projectMoney,$xm,2);
        }

        return $res;

    }

    // 员工小程序数据模块-客户分析
    public function getCustomerStistics($request){

        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));
            $endTime = strtotime(date('Y-m-t 23:59:59',time()));

            $request['startTime'] = $startTime;
            $request['endTime'] = $endTime;

            $st = date('Y-m-01',time());

            $et = date('Y-m-t',time());

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

                $st = $request['time'];

                $et = $request['time'];

            }else{

                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        $is_shop_array = ['2' => 1,'1' =>2];

        $shopIds = json_decode($request['shop_id'],true) ?? array();

        $newShopIds = [];

        if(is_array($shopIds)){

            foreach ($shopIds as $key => $value) {

                array_push($newShopIds,$value);

            }

        }else{

            // $newShopIds = [];

            array_push($newShopIds,$shopIds);

        }

        $newRequest['startTime'] = $startTime;

        $newRequest['endTime'] = $endTime;

        $newRequest['shopIds'] = $newShopIds;

        $person_id = isset($request['shop_person_id'])?$request['shop_person_id']:0;
        $sysModel = new SysModel();
        $position_id = $sysModel->getPersonPositionId($person_id);
        if(!empty($position_id)){
            $newRequest['shop_person_id'] = $person_id;
        }

        $model = new MiniStisticsModel();

        $newVip = $model->getNewVip($newRequest); // 新增会员数

        $comeInByOffLine = $model->getComeInNum(0,[46,47,48,583,608],$newRequest); // 门头外联进店

        $comeInByZhuan = $model->getComeInNum(0,[49],$newRequest); // 转介绍进店

        $comeInByOnLine = $model->getComeInNum(1,[46,47,48,49,583,608],$newRequest); // 网络进店

        $cj_num_bh = $model->getCjNum(1,$newRequest); // 疤痕成交数

        $cj_num_xm = $model->getCjNum(2,$newRequest); // 项目成交数

        $jd_num_bh = $model->getComeInScarOrPorject([1,2,3,4,5,6,7,8,10],$newRequest); // 疤痘进店数

        $jd_num_xm = $model->getComeInScarOrPorject([9,11,12],$newRequest); // 项目进店数

        if($jd_num_bh['count']>0){

            $cj_rate_bh = bcmul(bcdiv($cj_num_bh['count'],$jd_num_bh['count'],4),100,2)."%";

        }else{

            $cj_rate_bh = "0.00%";

        }

        if($jd_num_xm['count']>0){

            $cj_rate_xm = bcmul(bcdiv($cj_num_xm['count'],$jd_num_xm['count'],4),100,2)."%";

        }else{

            $cj_rate_xm = "0.00%";

        }

        $res = [
            'newVip' => $newVip['count'],

            'jd_mentou' => $comeInByOffLine['count'],

            'jd_zhuan' => $comeInByZhuan['count'],

            'jd_wangluo' => $comeInByOnLine['count'],

            'cj_num_bh' => $cj_num_bh['count'],

            'cj_num_xm' => $cj_num_xm['count'],

            'jd_num_bh' => $jd_num_bh['count'],

            'jd_num_xm' => $jd_num_xm['count'],

            'cj_rate_bh' => $cj_rate_bh,

            'cj_rate_xm' => $cj_rate_xm,
        ];

        return $res;
    }

    // 员工小程序数据模块-员工数据
    public function getStaffStistics($request)
    {



        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));

            $endTime = strtotime(date('Y-m-t 23:59:59',time()));

            $request['startTime'] = $startTime;

            $request['endTime'] = $endTime;

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

            }else{

                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        $newRequest['startTime'] = $startTime;

        $newRequest['endTime'] = $endTime;


        // 员工列表
        $staffIds = json_decode($request['staffList'],true) ?? array();

        $newStaffIds = [];

        foreach ($staffIds as $key => $value) {

            array_push($newStaffIds,$value);

        }

        $newRequest['staffList'] = $newStaffIds;

        // 门店列表
        $shopIds = json_decode($request['shop_id'],true) ?? array();

        $newShopIds = [];

        array_push($newShopIds,$shopIds);

        $newRequest['shop_id'] = $newShopIds;

        $model = new MiniStisticsModel();

        if($request['position_id'] == 9){

            $newOrder = $model->newOrder($newRequest); // 新单

            $repairOrder = $model->repairOrder($newRequest); // 补单

            $experience = $model->experience($newRequest); // 体验

            $serviceLog = $model->serviceLog($newRequest); // 护理次数

            $serviceNums = $model->serviceNums($newRequest); // 护理人数

            $zhuanNums = $model->zhuanNums($newRequest); // 转介绍业绩

            $waiLianNums = $model->waiLianNums($newRequest); // 外联人数

            $res = [

                'newOrder' => $newOrder[0]['newOrder'],

                'repairOrder' => $repairOrder[0]['repairOrder'],

                'experience' => $experience[0]['experience'],

                'serviceLog' => $serviceLog[0]['serviceLog'],

                'serviceNums' => $serviceNums[0]['serviceNums'],

                'zhuanNums' => $zhuanNums[0]['zhuanNums'],

                'waiLianNums' => $waiLianNums[0]['waiLianNums'],

            ];

        }else{

            if($request['tabTitle'] == '新单业绩'){

                $res = $model->newOrder($newRequest);

            }

            if($request['tabTitle'] == '补单业绩'){

                $res = $model->repairOrder($newRequest);

            }

            if($request['tabTitle'] == '体验成交'){

                $res = $model->experience($newRequest);

            }

            if($request['tabTitle'] == '护理次数'){

                $res = $model->serviceLog($newRequest);

            }

            if($request['tabTitle'] == '护理人数'){

                $res = $model->serviceNums($newRequest);

            }

            if($request['tabTitle'] == '转介绍数'){

                $res = $model->zhuanNums($newRequest);

            }

            if($request['tabTitle'] == '外联人数'){

                $res = $model->waiLianNums($newRequest);

            }

        }





        // $request['msg'] = 'model';

        return [

            'position_id' => $request['position_id'],

            'title' => $request['tabTitle'],

            'list' => $res,

        ];
    }

    // 时间-门店 转换函数
    public function getTime($request){

        // 时间
        if($request['time'] == '选择时间'){

            $startTime = strtotime(date('Y-m-01',time()));
            $endTime = strtotime(date('Y-m-t 23:59:59',time()));

            $request['startTime'] = $startTime;
            $request['endTime'] = $endTime;

            $st = date('Y-m-01',time());

            $et = date('Y-m-t',time());

        }else{

            $strlength = strlen($request['time']);

            if($strlength>7){

                $startTime = strtotime($request['time']." 00:00:00");

                $endTime = strtotime($request['time']." 23:59:59");

                $st = $request['time'];

                $et = $request['time'];

            }else{
                $t = date('t',strtotime($request['time']));

                $st = $request['time'].'-01';

                $et = $request['time'].'-'.$t;

                $startTime = strtotime($st." 00:00:00");

                $endTime = strtotime($et." 23:59:59");

            }

        }

        // 门店
        $shopIds = json_decode($request['shop_id'],true) ?? array();

        return [

            'startTime' => $startTime, // 开始时间戳

            'endTime' => $endTime, // 结束时间戳

            'st' => $st, //开始日期

            'et' => $et, // 结束日期

            'shopIds' => $shopIds, // 门店
        ];

    }

    // 问卷调查是否展示
    public function isQuestion($request){

        $customer_id = $request['customer_id'];

        $cj_time = Db::name('customer')->where('id',$customer_id)->value('cj_time');

        if($cj_time>0){

            $msg = "成交顾客";

            $newTime = time();

            $timeStr = bcsub($newTime,$cj_time,0);

            $days = bcdiv($timeStr,86400,0);

            switch ($days) {
                case $days >= 300: // 成交10个月
                     $status = 10;
                     break;
                case $days >= 150: // 成交5个月
                     $status = 5;
                     break;
                case $days >= 90: // 成交3个月
                     $status = 3;
                     break;
                case $days >= 30: // 成交1月
                     $status = 1;
                     break;
            }

            // echo $days;

        }else{

            $msg = "未成交顾客";

        }

        return [

            'msg'  => $msg,

            'data' => $cj_time,

            'days' => $days,

            'status' => $status,

        ];

    }

    /**
     * 获取问卷调查表
     *
     */
    public function getQuestionnaire($request){

        $status = $request['status'] ?? '';

        $where = [];

        array_push($where,['status','=',$status]);

        $questionnaire = Db::name('questionnaire')->where($where)->column('qusetion_ids,id');

        // echo "<pre>";
        // print_r($questionnaire);
        // echo "</pre>";
        // exit;

        $question_list = explode(',',$questionnaire[0]['qusetion_ids']); // 题目列表

        $questionShow = [];

        foreach ($question_list as $key => $value) {

            $showItem = [];

            $where = [];

            array_push($where,['id','=',$value]);

            $question = Db::name('question')->where($where)->column('question_describe,question_answer,status');

            // echo "<pre>";
            // print_r($question);
            // echo "</pre>";
            // exit;

            $showItem['itemId'] = bcadd($key,1,0);

            $showItem['question_describe'] = $question[0]['question_describe'];

            $showItem['status'] = $question[0]['status'];

            $answer_list = explode(',',$question[0]['question_answer']); // 答案列表

            $answer_Show = [];

            foreach ($answer_list as $k => $v) {

                $answerItem = [];

                $where = [];

                array_push($where,['id','=',$v]);

                $answer_info = Db::name('question_answer')->where($where)->column('describe,score');

                // echo "<pre>";
                // print_r($answer_info);
                // echo "</pre>";
                // exit;

                $answerItem['num'] = bcadd($k,1,0);

                $answerItem['describe'] = $answer_info[0]['describe'] ?? '';

                $answerItem['score'] = $answer_info[0]['score'] ?? '';

                array_push($answer_Show,$answerItem);

            }

            $showItem['question_answer'] = $answer_Show;

            array_push($questionShow,$showItem);

        }

        // echo "<pre>";
        // print_r($questionShow);
        // echo "</pre>";
        // exit;

        $data = [];

        $data['id'] = $questionnaire[0]['id'];

        $data['list'] = $questionShow;

        return $data;
    }



    //员工小程序-我的预约-门店护理师列表
    public function getPersonByShop($request):array
    {
        $shop_id = $request['shop_id'];
        $data['list'] = [];

        // $data['list'] = Db::name('admin_user')
        // ->field('realname,shop_person_id')
        // ->where('shop_id',$shop_id)
        // ->where('is_status',0)
        // ->where('is_reservation',1)
        // ->select()
        // ->toArray();

        $data['list'] = Db::name('admin_user')
            ->alias('au')
            ->field('au.realname, au.shop_person_id')
            ->join('shop_person sp', 'au.shop_person_id = sp.id')
            ->where('au.shop_id', $shop_id)
            ->where('au.is_status', 0)
            ->where('sp.is_reservation', 1)
            ->select()
            ->toArray();

        return $data;
    }


    // 获取员工小程序-我的预约-列表
    public function getStaffBookList($request):array
    {
        $type = $request['type'];
        $date = $request['date'] ?? '';

        if ($type == 'PC')
        {
            $user_id = $request['user_id'];
            $shop_person_id = Db::name('admin_user')->where('id', $user_id)->value('shop_person_id');
        } else {
            $shop_person_id = $request['shop_person_id']??'';
        }

        if ($date)
        {
            $time = $date;
        }else{
            $time = date('Y-m-d', time());
        }

        $personIds = Db::name('shop_person')->column('id', 'name');
        $where = [];

        if ($type == 'future')
        {
            $start_time = strtotime($time);
            $end_time = strtotime($time . " 23:59:59");
            $where[] = ['status', '=', 0];
            if(empty($shop_person_id))
            {
                $shop_id = $request['shop_id'];
                if ($shop_id)
                {
                    $where[] = ['shop_id', '=', $shop_id];
                }
            }else
            {
                $where[] = ['shop_person_id', '=', $shop_person_id];
            }
            $where[] = ['is_use', '=', 0];
            $where[] = ['yy_time', 'between', "$start_time,$end_time"];
        }elseif ($type == 'past')
        {
            $start_time = strtotime($time);
            $end_time = strtotime($time . " 23:59:59");
            $where[] = ['status', '=', 0];
            if(empty($shop_person_id))
            {
                $shop_id = $request['shop_id'];
                if ($shop_id)
                {
                    $where[] = ['shop_id', '=', $shop_id];
                }
            }else
            {
                $where[] = ['shop_person_id', '=', $shop_person_id];
            }
            $where[] = ['is_use', '=', 1];
            $where[] = ['yy_time', 'between', "$start_time,$end_time"];
        }elseif ($type == 'PC')
        {
            $shopIds = $request['shopIds'];
            $shop_id = $request['shop_id'];
            $customer_name = $request['customer_name'];
            $name = $request['name'];
            $dealTime = $request['deal_time'];
            $status = $request['status'];

            if ($shopIds) {
                $where[] = ['b.shop_id', 'in', $shopIds];
            }

            if ($shop_id) {
                $where[] = ['b.shop_id', '=', $shop_id];
            }

            if ($customer_name) {
                $where[] = ['c.customer_name|c.telephone', 'like', $customer_name];
            }

            if ($name) {
                $shopPresonId = $personIds[$name];
                $where[] = ['b.shop_person_id', '=', $shopPresonId];
            }

            if ($dealTime) {
                $startTime = strtotime($dealTime);
                $endTime = strtotime($dealTime) + 86399;
                $where[] = ['b.yy_time', '>=', $startTime];
                $where[] = ['b.yy_time', '<=', $endTime];
            }

            if ($status)
            {
                $tommerDay = strtotime($time);
                switch ($status) {
                    case 1:
                        $where[] = ['b.status', '=', 0];
                        $where[] = ['b.is_use', '=', 1];
                        break;
                    case 2:
                        $where[] = ['b.status', '=', 0];
                        $where[] = ['b.is_use', '=', 0];
                        $where[] = ['b.yy_time', '>=', $tommerDay];
                        break;
                    case 3:
                        $where[] = ['b.status', '=', 0];
                        $where[] = ['b.is_use', '=', 0];
                        $where[] = ['b.yy_time', '<', $tommerDay];
                        break;
                    case 4:
                        $where[] = ['b.is_use', '=', 0];
                        $where[] = ['b.status', '=', 1];
                        break;
                }
            }
        }

        if ($type == 'PC')
        {
            $field = ['b.customer_id', 'b.shop_person_id', 'b.shop_id', 'b.yy_time', 'b.create_time', 'b.is_use_time', 'b.status', 'b.is_use'];
            $dataCount = Db::name('books')->alias('b')
                ->join('customer c', 'c.id=b.customer_id', 'LEFT')
                ->where($where)->count();
            $list = Db::name('books')->alias('b')
                ->join('customer c', 'c.id=b.customer_id', 'LEFT')
                ->where($where)
                ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                ->field($field)
                ->order('b.yy_time DESC')
                ->select()->toArray();
        }else{
            $list = Db::name('books')->where($where)->order('id DESC')->select()->toArray();
        }

        $customer_ids = array_values(array_unique(array_column($list, 'customer_id')));
        $shopPersonIds = array_values(array_unique(array_column($list, 'shop_person_id')));
        $shopIds = array_values(array_unique(array_column($list, 'shop_id')));

        $customer_info = Db::name('customer')->where('id', 'in', $customer_ids)->column('customer_name,telephone,membership_leve', 'id');
        $open_info = Db::name('mini_program_fans')->where('customerId', 'in', $customer_ids)->column('avatarUrl,openId', 'customerId');
        $staff_info = Db::name('shop_person')->where('id', 'in', $shopPersonIds)->column('name', 'id');
        $shop_names = Db::name('shop')->where('shop_id', 'in', $shopIds)->column('shop_name', 'shop_id');

        $showList = [];
        foreach ($list as $key => $value)
        {
            $length = '';
            $yy_time_str = $value['yy_time_str'] ?? '';
            if ($yy_time_str)
            {
                $yy_time_arr = explode(',', $value['yy_time_str']);
                $length = count($yy_time_arr) * 0.5;
                $end_time = date('H:i', ($value['yy_time'] + (1800 * count($yy_time_arr))));
            }else
            {
                $end_time = date('H:i', ($value['yy_time'] + 1800));
                $length = 0.5;
            }

            $one = [];
            $one['customer_name'] = $customer_info[$value['customer_id']]['customer_name'] ?? '';
            $one['telephone'] = $customer_info[$value['customer_id']]['telephone'] ?? '';
            $one['shop_name'] = $shop_names[$value['shop_id']] ?? '';
            $one['membership_leve'] = $customer_info[$value['customer_id']]['membership_leve'] ?? '';
            $one['staff_name'] = $staff_info[$value['shop_person_id']] ?? '';
            $one['yy_time'] = date('Y-m-d H:i', $value['yy_time']) ?? '';
            $one['yy_time_str'] = $value['yy_time_str'] ?? '';
            $one['yy_length'] = $length;
            $one['openId'] = $open_info[$value['customer_id']]['openId'] ?? '';
            $one['avatarUrl'] = $open_info[$value['customer_id']]['avatarUrl'] ?? '';
            $one['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $one['is_use_time'] = $value['is_use_time'] > 0 ? date('Y-m-d H:i:s', $value['is_use_time']) : '';
            $one['status'] = $value['status'];
            $one['is_use'] = $value['is_use'];

            if ($value['status'] == '0')
            {
                if ($value['is_use'] == '0')
                {
                    if ($time <= $one['yy_time'])
                    {
                        $one['jindu'] = '待核销';
                    }else{
                        $one['jindu'] = '已过期';
                    }
                } else {
                    $one['jindu'] = '已核销';
                }
            } else {
                $one['jindu'] = '已取消';
            }
            $showList[] = $one;
        }

        $data = [];
        if ($type == 'PC')
        {
            $data['dataCount'] = $dataCount;
        }
        $data['list'] = $showList;
        return $data;
    }

}
